using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using Kassandra.Core.Infrastructure.ResourceManagement;

namespace Kassandra.Core
{
    internal class ImageFactory
    {
        private static NameValueCollection characters = new NameValueCollection();

        public static string CreateFor(char character)
        {
            character = char.Parse(character.ToString().ToLower());
            string imagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName), String.Format("images\\{0}.tif", (int)character));

            
            if (!File.Exists(imagePath))
            {
                Console.WriteLine(string.Format(MessageManagement.For("ImageNotFound") + " {0}. " + MessageManagement.For("") + " {1}", character, imagePath));
                return character.ToString();
            }
           
            StringBuilder str = new StringBuilder();
            str.Append("<w:pict>");

            //if the image does not exist then load the binary data the first time and
            //save the randomly generated name into the collection.
            if (characters[character.ToString()] == null)
            {
                string imageName = Guid.NewGuid() + ".jpg";
                str.AppendFormat("<w:binData w:name=\"wordml://{0}\">", imageName);
                str.Append(LoadBinaryImage(imagePath));
                str.Append("</w:binData>");
                characters.Add(character.ToString(), imageName);
            }

            //str.Append("<v:shape id=\"_x0000_s1666\" type=\"#_x0000_t75\" style=\"width:70px;height:105px\">");
            str.Append("<v:shape id=\"_x0000_s1666\" type=\"#_x0000_t75\" style=\"width:35px;height:53px\">");
            str.AppendFormat("<v:imagedata src=\"wordml://{0}\" o:title=\"Signature\" />", characters[character.ToString()]);
            str.Append("</v:shape>");
            str.Append("</w:pict>");
            str.Append(Environment.NewLine);
            return str.ToString();
        }

        private static byte[] imageToByteArray(Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, ImageFormat.Jpeg);
            return ms.ToArray();
        }

        private static string LoadBinaryImage(string imagePath)
        {
            if (!File.Exists(imagePath))
                throw new FileNotFoundException(MessageManagement.For("ImageFileNotFound"), imagePath);
            
            using (Image image = Image.FromFile(imagePath))
            {
                return Convert.ToBase64String(imageToByteArray(image));
            }
        }
    }
}